package com.demo.pictureshow.controllers;

import com.demo.pictureshow.entity.Category;
import com.demo.pictureshow.entity.Goods;
import com.demo.pictureshow.service.CategoryService;
import com.demo.pictureshow.service.GoodsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

@Controller
@RequestMapping("/admin/goods")
public class AdminGoodsController {


    private static final Logger LOGGER = LoggerFactory.getLogger(AdminGoodsController.class);

    @Resource
    private CategoryService categoryService;

    @Resource
    private GoodsService goodsService;

    @RequestMapping("/list")
    public String list(Model model) {
        List<Goods> goodsList = goodsService.list();
        model.addAttribute("goodsList", goodsList);
        return "admin/goods_list";
    }

    @RequestMapping("/add_show")
    public String addShow(Model modle) {
        List<Category> categoryList = categoryService.list();
        modle.addAttribute("categoryList", categoryList);
        return "admin/goods_add";
    }

    @RequestMapping("/add_submit")
    public String addSubmit(Goods goods, MultipartFile file) {
        String imgFile = null;
        // 判断客户端是否上传了图片
        if (file.isEmpty()) {
            // 如果没有上传图片，使用默认图片
            imgFile = "/img/mr.jpg";
        } else {
            File f = getUploadedFile(file.getOriginalFilename());
            try {
                // 将上传的文件存储到指定的磁盘位置
                file.transferTo(f);
                // 记录上传文件的web访问路径
                imgFile = "/up_file/" + f.getName();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        // 设置good对象的文件路径
        goods.setPicture(imgFile);
        // 保存文件
        goodsService.insert(goods);
        // 跳转到商品查询界面
        return "redirect:admin/goods/list";
    }

    @RequestMapping("/update_show")
    public String updateShow(Integer goodsId, Model model) {
        Goods goods = goodsService.find(goodsId);
        List<Category> categoryList = categoryService.list();
        model.addAttribute("goods", goods);
        model.addAttribute("categoryList", categoryList);
        return "admin/goods_update";

    }

    @RequestMapping("/update_submit")
    public String updateSubmit(Goods goods, MultipartFile file) {
        if (!file.isEmpty()) {
            File f = getUploadedFile(file.getOriginalFilename());
            try {
                // 将上传的文件存储到指定的磁盘位置
                file.transferTo(f);
                goods.setPicture("/up_file/" + f.getName());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 保存文件
        goodsService.update(goods);
        // 跳转到商品查询界面
        return "redirect:admin/goods/list";
    }

    /**
     * 根据源上传文件名称获取服务器上加了UUID的文件对象
     * @param fileName 源文件名
     * @return 文件对象
     */
    private File getUploadedFile(String fileName) {
        String randomFileName = UUID.randomUUID() + "-" + fileName;
        URL resource = this.getClass().getClassLoader().getResource("");
        File file = new File(Objects.requireNonNull(resource).getPath(), randomFileName);
        if (!file.getParentFile().exists()) {
            if (!file.mkdirs()) {
                LOGGER.error("newFile=>{}, mkdirs failed", file.getPath());
            }
        }
        return file;
    }

}
